/**
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { message, xhr } from '@/soar';

const request = xhr.create({
  baseURL: 'http://localhost:8999/generator',
  timeout: 60000,
  headers: { 'Content-Type': 'application/json;' },
});

request.responseInterceptor.add((res: any) => {
  if (res.data.success) {
    return res.data.data;
  }
  const error: any = new Error(res.data.msg);
  error.response = res;
  throw error;
});

request.catchInterceptor.add((err: any, config: any) => {
  if (!config.errorMsg || !err.response) {
    return;
  }
  const res = err.response;
  const data = res.data || {};

  switch (res.status) {
    case 400:
      if (Array.isArray(data.errors)) {
        // 自行解析错误提示
        data.msg = data.errors.map((item: any) => item.defaultMessage).join('，');
      }
      break;
    case 404:
      data.msg = '404：访问资源不存在';
      break;
    case 502:
      data.msg = '502：访问资源不存在';
      break;
    case 503:
      data.msg = '503：访问资源不存在';
      break;
    default:
      break;
  }

  const errMsg = typeof config.errorMsg === 'string' ? config.errorMsg : data.msg || '请求出现错误，请稍后再试';
  message.error({
    title: `${config.title || '操作'}失败`,
    message: errMsg,
  });
});

export function tableList(params?: any) {
  return request.get('/tableList', { params });
}

export function tableInfo(tableName: string) {
  return request.get('/tableInfo', {
    params: { tableName },
  });
}

export function generate(tableInfo: any) {
  return request.post('/generate', {
    data: tableInfo,
  });
}
